﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;

namespace FFSupplier.Common.Helper
{
    public class MSCRMHELPER
    {
        private OrganizationServiceProxy _service;

        public OrganizationServiceProxy CrmService
        {
            get { return _service; }
            set { _service = value; }
        }

        private string _discoveryUri;
        private string _organizationUri;
        private string _orgName;
        private string _userName;
        private string _password;
        private string _domain;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="discoveryUri"></param>
        /// <param name="organizationUri"></param>
        /// <param name="orgName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        public MSCRMHELPER(string discoveryUri, string organizationUri, string orgName, string userName, string password, string domain)
        {
            _discoveryUri = discoveryUri;
            _organizationUri = organizationUri;
            _orgName = orgName;
            _userName = userName;
            _password = password;
            _domain = domain;

            CrmService = OrganizationServiceProxyInit();
        }
        public MSCRMHELPER()
        {
            _discoveryUri = GetConfigValue("crmurl");
            _organizationUri = GetConfigValue("crmurl");
            _orgName = GetConfigValue("OrgName");
            _userName = GetConfigValue("adminusername");
            _password = GetConfigValue("adminuserpassword");
            _domain = GetConfigValue("adminuserdomainname");
            CrmService = OrganizationServiceProxyInit();

        }

        /// <summary>
        ///     获得配置项的数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected string GetConfigValue(string key)
        {
            return ConfigurationManager.AppSettings.Get(key);
        }

        private OrganizationServiceProxy OrganizationServiceProxyInit()
        {
            //to ignore certificates errors
            ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertificatePolicy;

            string DiscoveryUri = _discoveryUri + "/XRMServices/2011/Discovery.svc";
            IServiceConfiguration<IDiscoveryService> discoveryConfiguration = ServiceConfigurationFactory.CreateConfiguration<IDiscoveryService>(new Uri(DiscoveryUri));
            AuthenticationProviderType endpointType = discoveryConfiguration.AuthenticationType;

            OrganizationServiceProxy organizationServiceProxy = null;
            if (endpointType == AuthenticationProviderType.ActiveDirectory)
            {
                //AD
                string url = "//" + _orgName + "/XRMServices/2011/Organization.svc";
                Uri OrganizationUri = new Uri(_organizationUri + url);

                ClientCredentials clientCredentials = new ClientCredentials();
                clientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(_userName, _password, _domain);

                organizationServiceProxy = new OrganizationServiceProxy(OrganizationUri, null, clientCredentials, null);
            }
            else if (endpointType == AuthenticationProviderType.Federation)
            {
                //IFD  
                string OrganizationUri = _organizationUri + "/XRMServices/2011/Organization.svc";
                //string OrganizationUri = @"https://auvuat.foton.com.cn/Develop/XRMServices/2011/Organization.svc";

                ClientCredentials userCredentials = new ClientCredentials();
                userCredentials.UserName.UserName = _domain + "\\" + _userName; ;
                userCredentials.UserName.Password = _password;


                SecurityTokenResponse userResponseWrapper = discoveryConfiguration.Authenticate(userCredentials);
                var _discServiceProxy = new DiscoveryServiceProxy(discoveryConfiguration, userResponseWrapper);
                IServiceConfiguration<IOrganizationService> serviceConfiguration = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(new Uri(OrganizationUri));
                organizationServiceProxy = new OrganizationServiceProxy(serviceConfiguration, userResponseWrapper);
                organizationServiceProxy.EnableProxyTypes();
            }


            //QueryByAttribute query = new QueryByAttribute("systemuser");
            //query.AddAttributeValue("fullname", "systemuser");
            //query.ColumnSet = new ColumnSet(true);

            //EntityCollection ec = organizationServiceProxy.RetrieveMultiple(query);

            return organizationServiceProxy;
        }

        private bool AcceptAllCertificatePolicy(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        /// <summary>
        /// 实体禁用
        /// </summary>
        /// <param name="logicalName"></param>
        /// <param name="id"></param>
        public void Forbidden(string logicalName, Guid id)
        {
            Microsoft.Xrm.Sdk.OptionSetValue state = new Microsoft.Xrm.Sdk.OptionSetValue();
            Microsoft.Xrm.Sdk.OptionSetValue status = new Microsoft.Xrm.Sdk.OptionSetValue();
            state.Value = 1;
            status.Value = 2;

            EntityReference moniker = new EntityReference(logicalName, id);

            OrganizationRequest request = new OrganizationRequest() { RequestName = "SetState" };
            request["EntityMoniker"] = moniker;
            request["State"] = state;
            request["Status"] = status;
            CrmService.Execute(request);
        }

        /// <summary>
        /// 实体激活
        /// </summary>
        /// <param name="logicalName"></param>
        /// <param name="id"></param>
        public void UnForbidden(string logicalName, Guid id)
        {
            Microsoft.Xrm.Sdk.OptionSetValue state = new Microsoft.Xrm.Sdk.OptionSetValue();
            Microsoft.Xrm.Sdk.OptionSetValue status = new Microsoft.Xrm.Sdk.OptionSetValue();
            state.Value = 0;
            status.Value = 1;

            EntityReference moniker = new EntityReference(logicalName, id);

            OrganizationRequest request = new OrganizationRequest() { RequestName = "SetState" };
            request["EntityMoniker"] = moniker;
            request["State"] = state;
            request["Status"] = status;
            CrmService.Execute(request);
        }
    }
}

